<template>
  <div class="page-same-city">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{ $t("shop.sameCityDelFun") }}
      </div>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item :label="$t('shop.enableStatus') + '：'">
        <div>
          <el-switch
            v-model="dataForm.status"
            @change="onSwitchSameCity()"
          />
          <span class="status-tips">{{ $t("shop.deliSerProByYou") }}</span>
        </div>
      </el-form-item>
      <el-form-item :label="$t('shop.charges') + '：'">
        <div>
          <div>
            <el-radio
              v-model="dataForm.chargeType"
              :label="1"
            >
              {{ $t("shop.chaDelFeeByReg") }}
            </el-radio>
            <el-radio
              v-model="dataForm.chargeType"
              :label="2"
            >
              {{ $t("shop.delFeeChaDis") }}
            </el-radio>
          </div>
          <span
            v-if="dataForm.chargeType === 1"
            style="color: gray"
          >{{ $t("shop.chaFixDelFeeByRe") }}</span>
          <span
            v-if="dataForm.chargeType === 2"
            style="color: gray"
          >{{ $t("shop.byWalkDis") }}</span>
        </div>
      </el-form-item>
      <el-form-item
        :label="$t('shop.startingFeeY') + '：'"
        prop="startingFee"
      >
        <el-col :span="6">
          <el-input-number
            v-model="dataForm.startingFee"
            :max="100000"
            :placeholder="$t('shop.startingFee')"
            :precision="2"
            :step="0.01"
            :min="0.0"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        v-if="dataForm.chargeType === 1"
        :label="$t('shop.deliveryFeeY') + '：'"
        prop="deliveryFee"
      >
        <el-col :span="6">
          <el-input-number
            v-model="dataForm.deliveryFee"
            :max="100000"
            :placeholder="$t('shop.deliveryFee')"
            :min="0.00"
            :precision="2"
            :step="0.01"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        v-if="dataForm.chargeType === 2"
        :label="$t('shop.costAllocation') + '：'"
        style="color: gray"
        prop="headDistance"
      >
        <el-input-number
          v-model="dataForm.headDistance"
          :max="100000"
          :precision="1"
          :min="0.1"
          :step="0.1"
        />
        <span>{{ $t("shop.withinKm") }}</span>
        <el-input-number
          v-model="dataForm.deliveryFee"
          :max="100000"
          :min="0.00"
          :precision="2"
          :step="0.01"
        />
        <span>{{ $t("shop.yuanToChaDelFee") }}</span>
        <el-input-number
          v-model="dataForm.overDistance"
          :max="100000"
          :precision="1"
          :step="0.1"
          :min="0.1"
        />
        <span>km，{{ $t("shop.incInDelFees") }}</span>
        <el-input-number
          v-model="dataForm.overDistanceFee"
          :max="100000"
          :precision="2"
          :step="0.01"
          :min="0.01"
        />
        <span>{{ $t("admin.dollar") }}。</span>
      </el-form-item>
      <el-form-item
        :label="$t('shop.renewalCharge') + '：'"
        prop="prodName"
        style="color: gray"
      >
        <span>{{ $t("shop.commodityWeight") }}</span>
        <el-input-number
          v-model="dataForm.freeWeight"
          :max="100000"
          :precision="2"
          :step="0.01"
          :min="0.01"
          :placeholder="$t('shop.pleaseEnterTheWeight')"
        />
        <span>{{ $t("shop.noExtraCharge") }}</span>
        <el-input-number
          v-model="dataForm.overWeight"
          :max="100000"
          :precision="2"
          :step="0.01"
          :min="0.01"
          :placeholder="$t('shop.pleaseEnterTheWeight')"
        />
        <span>kg，{{ $t("shop.renewalFeeIncrease") }}</span>
        <el-input-number
          v-model="dataForm.overWeightFee"
          :max="100000"
          :precision="2"
          :step="0.01"
          :min="0.01"
        />
        <span>{{ $t("admin.dollar") }}。</span>
      </el-form-item>
      <el-form-item
        :label="$t('shopProcess.addr') + '：'"
        prop="currentAddr"
      >
        <el-cascader
          ref="cascaderAddrRef"
          v-model="dataForm.currentAddr"
          :options="addrList"
          :props="addrListTreeProps"
          :placeholder="$t('shopProcess.addrInputTips')"
          @change="onHandleAddrChange"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shopProcess.detailAddr') + '：'"
        prop="shopAddress"
      >
        <el-input
          v-model="dataForm.shopAddress"
          :placeholder="$t('shopProcess.detailAddrInputTips')"
          maxlength="50"
          style="width: 200px"
          @blur="onMapEnable"
          @change="onMapLocation"
        />
      </el-form-item>
      <!--map组件-->
      <el-form-item
        prop="brief"
        :label="$t('product.deliveryArea') + '：'"
      >
        <div class="map">
          <tmap
            ref="tmapRef"
            :lat-lng="latLng"
            :is-update-coordinates="false"
            :is-show-control="true"
            @set-polygon-path="onSetPolygonPath"
            @change-lat-lng="onChangeLatLng"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn text-btn"
          @click="onResetMapPoint()"
        >
          {{ $t("shop.resetMap") }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="onSubmit"
        >
          {{ $t("order.save") }}
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import Big from 'big.js'
import { ElMessage } from 'element-plus'
import { removeHeadAndTailSpaces } from '@/utils/validate'

const dataRule = {
  startingFee: [{ required: true, message: $t('shop.stargFeeCannoEmp'), trigger: 'blur' }],
  deliveryFee: [{ required: true, message: $t('shop.delFeeCannoEmp'), trigger: 'blur' }],
  currentAddr: [
    { required: true, message: $t('shopProcess.addrInputTips'), trigger: ['blur', 'change'] }
  ],
  shopAddress: [
    { required: true, message: $t('shopProcess.detailAddrNotEmpty'), trigger: ['blur', 'change'] }
  ]
}
let TMap = window.TMap
onMounted(() => {
  if (TMap) {
    onGetSameCityDetail()
  } else {
    onGetTMap()
  }
  onGetAddrList()
})
let time = null
const onGetTMap = () => {
  time = setTimeout(() => {
    TMap = window.TMap
    if (TMap) {
      time = null
      onGetSameCityDetail()
    } else {
      onGetTMap()
    }
  }, 500)
}

// 获取店铺详情数据
const isConfigureAreaDefault = ref(true)
const dataForm = ref({
  chargeType: 1,
  samecityId: 0,
  shopId: 0,
  status: false,
  polygonPath: [],
  startingFee: 0.0,
  deliveryFee: 0.0,
  headDistance: 0.0,
  overDistance: 0.0,
  overDistanceFee: 0.0,
  freeWeight: 0.0,
  overWeight: 0.0,
  overWeightFee: 0.0,
  province: '',
  provinceId: '',
  city: '',
  cityId: '',
  area: '',
  areaId: '',
  shopAddress: '',
  shopLat: 39.908821,
  shopLng: 116.397469
})
const polygonPath = ref([])
const tmapRef = ref(null)

// 设置默认值则初始定位到默认值，否则根据ip定位
const latLng = ref({
  lat: 39.908821,
  lng: 116.397469
})
/**
 * 获取店铺同城配送的配置
 */
const onGetSameCityDetail = () => {
  http({
    url: http.adornUrl('/delivery/sameCity/getSameCityInfo'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      dataForm.value = data
      polygonPath.value = data.polygonPath || []
      dataForm.value.status = dataForm.value.status === 1
      dataForm.value.currentAddr = [
        data.provinceId,
        data.cityId,
        data.areaId
      ]
      latLng.value = {
        lat: dataForm.value.shopLat,
        lng: dataForm.value.shopLng
      }
    }
    if (!dataForm.value.samecityId || !polygonPath.value || polygonPath.value.length <= 0) {
      const points = onGetPoint({ shopLng: dataForm.value.shopLng, shopLat: dataForm.value.shopLat })
      polygonPath.value.push(...points)
      nextTick(() => {
        isConfigureAreaDefault.value = true
        tmapRef.value?.onInitGemotryEditor(polygonPath.value)
        tmapRef.value?.onSetZoom(13)
      })
    } else {
      isConfigureAreaDefault.value = false
      const polygonArray = JSON.parse(JSON.stringify(polygonPath.value))
      polygonPath.value.length = 0
      polygonArray.forEach((item) => {
        const point = new TMap.LatLng(item.lat, item.lng)
        polygonPath.value.push(point)
      })
      nextTick(() => {
        tmapRef.value?.onInitGemotryEditor(polygonPath.value)
        tmapRef.value?.onSetZoom(13)
      })
    }
  })
}

const addrListTreeProps = reactive({
  value: 'areaId',
  label: 'areaName'
})
const addrList = ref([]) // 地址-省市区
/**
 * 地址
 */
const onGetAddrList = () => {
  http({
    url: http.adornUrl('/admin/area/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    addrList.value = treeDataTranslate(data, 'areaId', 'parentId')
    addrList.value = onRemoveNotThirdCategoryItem(addrList.value)
  })
}

const onRemoveNotThirdCategoryItem = (treeData) => {
  if (treeData[0] && treeData[0].level === 3) {
    // 当为三级分类时，不需要再判断
    return treeData
  }

  const firstCategory = treeData
  const length = firstCategory.length
  for (let i = 0, index = 0; i < length; i++) {
    if (firstCategory[index].children && firstCategory[index].children !== undefined && (firstCategory[index].children.some(item => item.children) || firstCategory[index].level !== 1)) {
      const secondCategory = firstCategory[index].children
      firstCategory[index].children = onRemoveNotThirdCategoryItem(secondCategory)
    } else {
      firstCategory.splice(index, 1)

      // 当前位置的元素已经被删除，当前位置索引不用++
      continue
    }
    index++
  }
  return firstCategory
}

/**
 * 监听地址改变
 */
const cascaderAddrRef = ref(null)
const onHandleAddrChange = (value) => {
  if (value.length > 0) {
    const labels = cascaderAddrRef.value.getCheckedNodes()[0]?.pathLabels
    dataForm.value.province = labels[0]
    dataForm.value.provinceId = value[0]
    dataForm.value.city = labels[1]
    dataForm.value.cityId = value[1]
    dataForm.value.area = labels[2]
    dataForm.value.areaId = value[2]
    onMapLocation()
  }
}

// 腾讯地图
const onMapLocation = () => {
  let address = ''
  const { provinceId, province, cityId, city, areaId, area, shopAddress } = dataForm.value
  // 选择省市区时，定位地图
  if (provinceId) {
    address = province
    tmapRef.value.onSetZoom(6)
    if (cityId) {
      address = address + city
      tmapRef.value.onSetZoom(10)
      if (areaId) {
        address = address + area
        tmapRef.value.onSetZoom(13)
        if (shopAddress) {
          // 详细地址
          address = address + shopAddress
          tmapRef.value.onSetZoom(13)
        }
      }
    }
  }
  if (address) {
    tmapRef.value.onGetLocation(address).then(res => {
      onChangeLatLng(res)
    })
  }
}

/**
 * 获取区域点坐标
 * @param latLng
 * @returns {[TMap.LatLng,TMap.LatLng,TMap.LatLng,TMap.LatLng]}
 */
const onGetPoint = (latLng) => {
  const lng = new Big(Number.parseFloat(latLng.shopLng))
  const lat = new Big(Number.parseFloat(latLng.shopLat))
  const point1 = new TMap.LatLng(
    Number.parseFloat(lat),
    Number.parseFloat(lng)
  )
  const point2 = new TMap.LatLng(
    Number.parseFloat(lat.plus(0.01)),
    Number.parseFloat(lng.plus(0.01))
  )
  const point3 = new TMap.LatLng(
    Number.parseFloat(lat.plus(0.02)),
    Number.parseFloat(lng.plus(0.02))
  )
  const point4 = new TMap.LatLng(
    Number.parseFloat(lat.plus(0.01001)),
    Number.parseFloat(lng.plus(0.01001))
  )
  return [point1, point2, point3, point4]
}

// 修改经纬度
const onChangeLatLng = (latLngInfo) => {
  const { lng, lat } = latLngInfo
  latLng.value = {
    lat,
    lng
  }
  dataForm.value.shopLng = lng
  dataForm.value.shopLat = lat
  // 更改坐标点后，重新设置地图选区
  const points = onGetPoint({ shopLng: dataForm.value.shopLng, shopLat: dataForm.value.shopLat })
  polygonPath.value = []
  polygonPath.value.push(...points)
  nextTick(() => {
    isConfigureAreaDefault.value = true
    tmapRef.value?.onResetGemotryEditor(polygonPath.value)
  })
}

const onSwitchSameCity = () => {
  if (
    dataForm.value === null ||
    dataForm.value.shopLng === '' ||
    dataForm.value.shopLng === null ||
    dataForm.value.shopLat === null ||
    dataForm.value.shopLat === ''
  ) {
    dataForm.value.status = !dataForm.value.status
  }
}

const dataFormRef = ref(null)
const onResetMapPoint = () => {
  isConfigureAreaDefault.value = true
  dataForm.value.polygonPath = null
  polygonPath.value = null
  polygonPath.value = onGetPoint({ shopLng: dataForm.value.shopLng, shopLat: dataForm.value.shopLat })
  tmapRef.value?.onResetGemotryEditor(polygonPath.value)
  ElMessage({
    message: $t('publics.operation'),
    type: 'success',
    duration: 1500
  })
}

// 表单提交
const isDataTrue = ref(false)

const onSubmit = () => {
  onCheckData()
  if (!isDataTrue.value) {
    return
  }
  dataForm.value.polygonPath = polygonPath.value
  if (isConfigureAreaDefault.value && dataForm.value.status === false) dataForm.value.polygonPath = []

  dataForm.value.status = dataForm.value.status ? 1 : 0
  dataFormRef.value.validate(valid => {
    if (valid) {
      http({
        url: http.adornUrl('/delivery/sameCity'),
        method: dataForm.value.samecityId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        dataForm.value.status = dataForm.value.status === 1
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500
        })
      })
    }
  })
}
const onCheckData = () => {
  if (dataForm.value.overWeightFee == null) {
    onErrorMsg($t('shop.costCannotBeEmpty'))
    isDataTrue.value = false
    return
  }
  if (dataForm.value.chargeType === 2 && dataForm.value.overDistanceFee == null) {
    onErrorMsg($t('shop.excDisFeeCanBeEm'))
    isDataTrue.value = false
    return
  }
  if (
    dataForm.value.chargeType === 2 &&
    (dataForm.value.headDistance == null || dataForm.value.overDistance == null)
  ) {
    onErrorMsg($t('shop.distanceCannotBeEmpty'))
    isDataTrue.value = false
    return
  }
  if (!dataForm.value.freeWeight == null || !dataForm.value.overWeight == null) {
    onErrorMsg($t('shop.weightCannotBeEmpty'))
    isDataTrue.value = false
    return
  }
  if (polygonPath.value != null && polygonPath.value.length > 12) {
    onErrorMsg($t('shop.polygonPathOverNum'))
    isDataTrue.value = false
    return
  }
  if (dataForm.value.status && isConfigureAreaDefault.value) {
    onErrorMsg($t('shop.setArea'))
    isDataTrue.value = false
    return
  }
  isDataTrue.value = true
}
const onErrorMsg = message => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}
const onSetPolygonPath = (data) => {
  polygonPath.value.length = 0
  polygonPath.value.push(...data.paths)
  isConfigureAreaDefault.value = false
}
const onMapEnable = () => {
  dataForm.value.shopAddress = dataForm.value.shopAddress ? removeHeadAndTailSpaces(dataForm.value.shopAddress) : dataForm.value.shopAddress
}

onUnmounted(() => {
  if (time) {
    clearTimeout(time)
  }
})
</script>

<style lang="scss" scoped>
.page-same-city {
  .status-tips {
    color: #999999;
    margin-left: 20px;
  }
  .map {
    width: 50%;
    height: 500px;
  }
}
</style>
